//
//  AppDelegate.m
//  JWT
//
//  Created by Apple on 2017/1/1.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "AppDelegate.h"
#import "APPLanchViewController.h"
#import "JWTAppTabBarTheme.h"
#import <AlipaySDK/AlipaySDK.h>
// 键盘管理
#import "IQKeyboardManager.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

SHARED_INSTANCE_IMPLEMENTATION(AppDelegate);
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    APPLanchViewController * lanchVC  = [[APPLanchViewController alloc] init];
    self.window.rootViewController = lanchVC;
    [self.window makeKeyAndVisible];
    
    [self isAutoLogin];
    
    [self initAppTabBar];
    
    // 键盘管理
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    return YES;
}
-(void) initAppTabBar{
    [[JWTAppTabBarTheme sharedInstance] customizeInterfaceUIColor:RGB_WhiteBackGround];
    RDVTabBarController *tabbarVC = [[JWTAppTabBarTheme sharedInstance] setupViewControllers];
    [[JWTAppTabBarTheme sharedInstance] customizeTabBarForController:tabbarVC];
    self.window.rootViewController = tabbarVC;
}


/**
 是否自动登录
 */
- (void)isAutoLogin {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *tokenid = [userDefaults objectForKey:@"tokenID"];
    NSString *tel = [userDefaults objectForKey:@"tel"];
    NSString *password = [userDefaults objectForKey:@"passWord"];
    
    if (tokenid && tel && password) { // 存在就自动登录
        // 自动登录
        dispatch_semaphore_t loginSemaphore = dispatch_semaphore_create(0);
        
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        
        self.afnCompletionQueue = queue;
        
        __block BOOL isAutoLoginSuccess = NO;
        __block BOOL isTimeOut = NO;
        
        dispatch_async(queue, ^{
            
            NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getHttpsUrlWithActionLogin];
            NSDictionary *dict = @{@"tel":tel,@"password":password};
            
            [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
                if (model) {
                    if ([[model objectForKey:@"code"] integerValue] == 200) { // 登录成功
                        APPDELEGATE.isLogin = YES;
                        APPDELEGATE.userInfo = [JWTUserInfo mj_objectWithKeyValues:[model objectForKey:@"data"] ];
                        //判断是否记住密码与自动登录
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:APPDELEGATE.userInfo.tel forKey:@"tel"];
                        [userDefaults setObject:APPDELEGATE.userInfo.name forKey:@"userName"];
                        [userDefaults setObject:password forKey:@"passWord"];
                        [userDefaults setObject:@"1" forKey:@"islogin"];
                        [userDefaults setObject:APPDELEGATE.userInfo.tokenid forKey:@"tokenID"];
                        [userDefaults synchronize];
                        
                        isAutoLoginSuccess = YES;
                    } else {
                        if (!isTimeOut) {
                            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                            [userDefaults setObject:@"" forKey:@"tel"];
                            [userDefaults setObject:@"" forKey:@"userName"];
                            [userDefaults setObject:@"" forKey:@"passWord"];
                            [userDefaults setObject:@"" forKey:@"tokenID"];
                            [userDefaults synchronize];
                        }
                    }
                }
                dispatch_semaphore_signal(loginSemaphore);
            }];
        });
        
        // 若10s无反应-应进入登录界面
        // 10s 后自动执行之后的代码 (DISPATCH_TIME_FOREVER)
        dispatch_semaphore_wait(loginSemaphore, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC));
        
        self.afnCompletionQueue = dispatch_get_main_queue();
        isTimeOut = YES;
        
        if (!isAutoLoginSuccess) {
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:@"" forKey:@"tel"];
            [userDefaults setObject:@"" forKey:@"userName"];
            [userDefaults setObject:@"" forKey:@"passWord"];
            [userDefaults setObject:@"" forKey:@"tokenID"];
            [userDefaults synchronize];
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"JWTAlipay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"JWTAlipay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}


@end
